import {isLogin} from "@/utils/auth.ts";
import {getCacheObj, setCacheObj} from "@/utils/cache.ts";
import {getDynamicLocalRoutes} from "@/router/dynamicLocalRoutes.ts"
import {queryRoleMenu} from "@/api/system";
//是否开启http路由 false则开启本地路由
const enableHttpRouter = true;
//加工好的路由
let outRoutes: any[] = []

//获取路由（加工好的）
export function getRoutes() {
  return outRoutes
}

// 添加路由的函数
function addRoute(routes: any[], router) {
  // 第一步：添加所有顶级路由
  routes.forEach(route => {
    try {
      router.addRoute(route);
    } catch (error) {
      console.error(`Failed to add top-level route ${route.name}:`, error);
    }
  });

  // 第二步：添加所有子路由
  routes.forEach(route => {
    if (route.children && route.children.length > 0) {
      route.children.forEach(childRoute => {
        try {
          router.addRoute(route.name, childRoute);
        } catch (error) {
          console.error(`Failed to add child route ${childRoute.name} to parent ${route.name}:`, error);
        }
      });
    }
  });
}

/**
 * 注册动态路由
 * @param router vueRouter
 * @param useCache 是否使用缓存
 * @param useDynamicLocalRoutes 使用本地静态数据的路由
 */
export async function registerDynamicRoutes(router: any, useCache = false) {
  console.log(`注册动态路由,mode: ${enableHttpRouter ? "http" : "local"} 是否使用缓存：${useCache}`)
  const modules = import.meta.glob('../views/**/**/*.vue')
  let data: any[] = [];
  if (!useCache) {
    if (!enableHttpRouter) {
      data = getDynamicLocalRoutes();
    } else {
      const res = await queryRoleMenu();
      data = res.data;
    }
    //深度克隆
    setCacheObj("menu", data)
  } else {
    data = getCacheObj("menu", []) as any[];
  }

  data.forEach(route => {
    if (route?.meta?.isFrame) {
      return;
    }
    route.path = route.path.startsWith('/') ? route.path : '/' + route.path;
    // 处理父级路由组件
    if (modules[`..${route.component}`]) {
      route.component = modules[`..${route.component}`]
    } else {
      console.warn(`Component not found for parent route: ${route.component}`);
      route.component = modules['../views/Layout.vue']; // 默认组件
    }
    if (route.children && route.children[0]) {
      route.redirect = `${route.path}/${route.children[0].path}`
    }
    // 处理子路由
    if (route.children && route.children.length > 0) {
      route.children.forEach(childRoute => {
        if (childRoute?.meta?.isFrame) {
          console.log(childRoute)
          return
        }
        // 构建完整的子路由路径
        if (route.path) {
          childRoute.path = `${childRoute.path}`
        }
        // 处理子路由组件
        if (modules[`..${childRoute.component}`]) {
          childRoute.component = modules[`..${childRoute.component}`]
        } else {
          console.warn(`Component not found for child route: ${childRoute.component}`);
          childRoute.component = modules['../views/NotFound.vue']; // 默认组件
        }
      });
    }
  });
  //添加到vueRouter
  addRoute(data, router)
  //暴露
  outRoutes = data;
  return data
}


// 从本地获取缓存路由以初始化动态路由,防止刷新页面路由丢失
export async function initDynamicRoutes(router: any) {
  try {
    if (isLogin()) {
      await registerDynamicRoutes(router, true)
    } else {

    }
  } catch (error) {
    console.error('Failed to register dynamic routes:', error);
  }
}
